<template>
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>客户公海</span>
        </div>
        <div style="display:flex;justify-content: space-between">
            <div v-if="!titleCurrentPanel">
                <el-input v-model="queryData.clientName" placeholder="客户名称" size="small"></el-input>
                <el-date-picker
                        size="small"
                        v-model="queryData.joinTime"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="创建日期"
                        end-placeholder="创建日期">
                </el-date-picker>
                <el-input v-model="queryData.companyName" placeholder="企业名称" size="small"></el-input>&nbsp;&nbsp;
                <el-button type="primary" size="small" @click="queryDataHandle(1, 10)">查询</el-button>
<!--                <el-divider direction="vertical"></el-divider>-->
                <el-button plain size="small" @click="resetQuery">重置</el-button>
            </div>
            <div v-if="!titleCurrentPanel" style="display:flex;">
                <el-button type="primary" size="small" @click="exportClientHandle">导出</el-button>
                <div style="width: 10px"></div>
                <el-button type="primary" size="small" @click="importVisible = true">导入</el-button>
                <el-dialog
                        title="导入客户"
                        :visible.sync="importVisible"
                        width="30%">
                    <el-upload
                            class="upload-demo"
                            style="display: flex;justify-content: center"
                            drag
                            ref="uploadExcel"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                            :action="$uri + '/api/customers/importCustomersUpdate/1_0'"
                            :data="{orgId: $store.getters.getUserInfo.orgId,orgNum: $store.getters.getUserInfo.orgNum,companyId: $store.getters.getUserInfo.companyId}">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    </el-upload>
                    <div style="display: flex;justify-content: center;align-items: center;margin-top: 20px">
                        只能上传 xls/xlsx/csv 文件，且不超过10MB
                        <el-button size="small" type="text" @click="downloadTemp" style="padding: 0;font-size: 14px">点击此处下载模板</el-button>
                    </div>
                </el-dialog>
            </div>

            <div v-if="titleCurrentPanel" style="display:flex;justify-content: space-between">
                <div>
                    <el-button plain size="small" @click="setEmpHandle">分配</el-button>
                    <el-button plain type="danger" size="small" @click="deleteClients">彻底删除</el-button>
                </div>
                <el-dialog title="分配成员" :visible.sync="allotVisible" width="60%" :close-on-click-modal="false">
                    <ListSelect @getData="getData" :listFields="listFields" :dataSource="memberData"/>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="allotVisible = false">返回</el-button>
                </span>
                </el-dialog>

            </div>
        </div>

        <div class="interspaceH"></div>

        <el-table @selection-change="tableRowChange" :data="dataSource" @row-click="openDetail"
                  :header-cell-style="{background:'#F3F4F7',color:'#555'}" style="width: 100%">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="clientName" label="名称"></el-table-column>
            <el-table-column prop="clientCompany" label="企业名称"></el-table-column>
            <el-table-column width="400" label="客户标签">
                <template slot-scope="scope">
                    <el-tag :key="index" v-for="(tag, index) in scope.row.tagList" style="margin-bottom: 10px">
                        {{ tag.clientTagsName }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="clientPhone" label="电话"></el-table-column>
            <el-table-column prop="clientDescription" label="描述"></el-table-column>
            <el-table-column prop="joinTime" label="创建时间" :formatter="formatter"></el-table-column>
        </el-table>

        <div class="interspaceH"></div>

        <el-pagination @size-change="queryDataHandle(pagePagination.currentPage,$event)"
                       @current-change="queryDataHandle($event,pagePagination.pageSize)"
                       :current-page="pagePagination.currentPage"
                       :page-sizes="pagePagination.pageSizes" :page-size="pagePagination.pageSize"
                       layout="total, sizes, prev, pager, next"
                       :total="pagePagination.total">
        </el-pagination>

        <ClientDetail ref="clientDetail"/>
    </el-card>
</template>

<script>
import axios from "axios";

const initQueryData = {
    clientName: '',//客户名称
    companyName: '',//企业名称
    joinTime: ''//创建时间
}

import ClientDetail from '@/views/customer/client/client_detail'
import ListSelect from "@/components/list_select/list_select"
import {requestFile} from "@/util/request";

export default {
    name: "index",
    components: {
        ClientDetail,
        ListSelect
    },
    data() {
        return {
            allotVisible: false,
            titleCurrentPanel: false,
            importVisible: false,
            multipleSelection: [],
            //查询表单
            queryData: {...initQueryData},
            //下拉列表种类
            dictionary: {},
            //字段转换
            fieldType: {
                joinTime: "datetime"
            },
            //列表数据
            dataSource: [],
            memberData: [],
            pagePagination: {
                currentPage: 1,
                pageSizes: [10, 15, 20, 25],
                pageSize: 10,
                total: 0
            },
            listFields: {
                deptName: "所属部门",
                empName: "员工名称",
            },
        }
    },
    mounted() {
        //初始化执行查询方法
        this.queryDataHandle(1, 10)
    },
    methods: {
        queryDataHandle(page = 1, row = 10) {
            let that = this;
            let queryData = that.queryData
            let payload = {
                ...queryData,
                clientType: '3',
                pageNum: page,
                pageSize: row
            }
            that.$request("/api/customers/getCustomersByParams/1_0", payload, "POST").then((data) => {
                that.dataSource = data.rows
                that.pagePagination['total'] = data.total
                that.pagePagination['pageSize'] = data.row
            })
        },
        resetQuery() {
            this.queryData = {...initQueryData}
        },
        tableRowChange(val) {
            if (val.length > 0) {
                this.titleCurrentPanel = true
            } else {
                this.titleCurrentPanel = false
            }
            this.multipleSelection = val;
        },
        formatter(row, column) {
            let field = column.property;
            let value = row[field];
            return this.$utils.formatterForLable(field, value, this.fieldType, this['dictionary'][field]);
        },
        exportClientHandle() {
            this.$requestFile("/api/customers/exportCustomers/1_0", {clientType: '3'}, "客户公海.xlsx")
        },
        downloadTemp() {
            this.$requestFile("/api/excel/downloadTemp/1_0?fileType=clients", "", "导入客户模板.xls")
        },
        importExcelHandle() {

        },
        openDetail() {
            this.$refs.clientDetail.open(true)
        },
        setEmpHandle() {
            let that = this
            that.$request("/api/emp/getAllEmp/1_0", {}, "POST").then((data) => {
                that.memberData = data.rows
                that.allotVisible = true
            })
        },
        getData(data) {
            let that = this

            let payload = {
                empId: data.empId,
                clientSize: this.multipleSelection.length,
            }

            that.$request("/api/clientClue/pushAddClientAlert/1_0", payload, "POST").then((data) => {

            }).then(() => {
                let clients = that.multipleSelection
                clients.map((item) => {
                    item['clientType'] = '1'
                    item['empId'] = data.empId

                    let payload = {
                        clientId: item.clientId,
                        clientName: item.clientName,
                        empId: data.empId,
                        empName: data.empName,
                        clientIsFriends: "false",
                        description: "管理员将该客户分配至员工：" + data.empName
                    }

                    that.$request("/api/clientHistory/insertClientFollow/1_0", payload, "POST").then((data) => {
                        that.memberData = data.rows
                        that.allotVisible = false
                        that.$message.success("分配成功")
                        that.queryDataHandle()
                    })
                })
            })
        },
        deleteClients() {
            let ids = []
            this.multipleSelection.map((item) => {
                ids.push(item.clientId)
            })
            this.$confirm('此操作将永久客户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let payload = {
                    clientIds: ids
                }
                this.$request("/api/customers/deleteCustomersByIds/1_0", payload, "POST").then((data) => {
                    this.$message.success("删除成功")
                    this.queryDataHandle()
                })
            })
        },
        beforeUploadHandle(file) {
            const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (!isExcel) {
                this.$message.error('只能是 xls/xlsx/csv 格式!');
                return false
            }
            if (file.size > 10 * 1024 * 1024) {
                this.$message.error('文件超出10M');
                return false
            }
        },
        uploadSuccess() {
            this.$message.success("导入成功");
            this.$refs.uploadExcel.clearFiles()
            this.importVisible = false
            this.queryDataHandle()
        },
        uploadError() {
            this.$message.error("导入失败");
        }
    }
}
</script>

<style scoped>
.box-card .el-input {
    width: 200px;
}

.el-card__body .el-select {
    width: 200px;
}
</style>
